package com.ebc.eservice.service.impl.login;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ebc.eservice.mapper.CardMapper;
import com.ebc.eservice.mapper.CompanyMapper;
import com.ebc.eservice.mapper.MenuMapper;
import com.ebc.eservice.mapper.RoleMapper;
import com.ebc.eservice.pojo.*;
import com.ebc.eservice.pojo.dto.MenuItem;
import com.ebc.eservice.pojo.dto.Route;
import com.ebc.eservice.util.JsonResult;
import com.ebc.eservice.util.JwtUtil;
import com.ebc.eservice.vo.user.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author: Joey
 * @Description:
 * @date:2022/9/19 1:22
 */
@Service
public class LoginServiceImp implements LoginService{
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private CompanyMapper companyMapper;

    //pc-login
    public JsonResult login(LoginUserVo emp) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(emp.getUserAccount(),emp.getPassword());
        // 通过AuthenticationManager的authenticate方法来进行用户认证 loadUserByUsername()的返回值
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 判断是否验证成功
        if(Objects.isNull(authenticate)){
            return JsonResult.fail("用户不存在");
//            throw new RuntimeException("用户名或密码错误");
        }
        // 在认证信息authenticate中获取登录成功后的用户信息
        UserDT user = (UserDT) authenticate.getPrincipal();
        String userId = user.getUser().getId().toString();

        List<EbcRole> roles = roleMapper.getUserRolesByUid(Integer.parseInt(userId));

        if(roles.get(0).getRoleCode().contains("v3")
                || roles.get(0).getRoleCode().contains("dba")
                || roles.get(0).getRoleCode().contains("sec")){

            HashMap<String,Object> map = new HashMap<>();
            List<EbcMenu> routeList = getMenuList(Integer.parseInt(userId));
            List<Route> menuList = getRouteMenu(routeList);
            String jwt = JwtUtil.createJWT(userId);

            if(roles.get(0).getRoleCode().contains("dba")){
                EbcCompany comapny = getComapny(102);
                map.put("companyInfo",comapny);
            }
            if(roles.get(0).getRoleCode().contains("v3")){
                EbcCompany comapny = getComapny(Integer.parseInt(userId));
                map.put("companyInfo",comapny);
            }
            if(roles.get(0).getRoleCode().contains("sec")){
                EbcCompany comapny = getComapny(102);
                map.put("companyInfo",comapny);
            }
            if(menuList.size() == 0){
                return JsonResult.fail("账号权限不匹配，重新输入");
            }
            map.put("token",jwt);
            map.put("user",user);
            map.put("menu",menuList);//所有菜单
            map.put("routes",routeList);
            redisTemplate.opsForValue().set("tk" + userId, user,60, TimeUnit.MINUTES);
            return JsonResult.success(map);
        }else{
            return JsonResult.fail("账号权限不匹配，重新输入");
        }
    }

    public JsonResult logout(){
        EbcUser loginUser = (EbcUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("注销用户: "+loginUser);
        int userid = loginUser.getId();
        redisTemplate.delete("tk"+userid);
        return JsonResult.success("注销成功");
    }

    //获取公司信息
    public EbcCompany getComapny(Integer userId){
        QueryWrapper<EbcCompany> wrapper = new QueryWrapper<>();
        wrapper.eq("possessor_id",userId);
        EbcCompany company = companyMapper.selectOne(wrapper);
        return company;
    }

    @Override
    public List<EbcMenu> getMenuList(Integer uid) {
        List<EbcRole> roles = roleMapper.getUserRolesByUid(uid); //uid
        List<EbcMenu> menuList = new ArrayList<>();
        List<String> list = new ArrayList<>();
        for (EbcRole s: roles) {
            list.add(s.getRoleCode());
        }
        for (int i = 0; i < 4; i++) {
            if(list.contains("dba")){
                System.out.println("[管理员进入]");
                menuList = menuMapper.getMenuList(4);
                break;
            } else if (list.contains("v3")){
                System.out.println("[公司管理员]");
                menuList = menuMapper.getMenuList(3);
                break;
            } else if (list.contains("sec")){
                System.out.println("[保安测试]");
                menuList = menuMapper.getMenuList(6);
                break;
            }else if (list.contains("c1")){
                System.out.println("[用户进入]");
                menuList = menuMapper.getMenuList(2);
                break;
            }else if(list.contains("v2")){
                System.out.println("[员工进入]");
                menuList = menuMapper.getMenuList(1);
                break;
            }else{
                System.out.println("三无账号");
            }
        }
        return menuList;
    }

    @Override
    public List<Route> getRouteMenu(List<EbcMenu> menuList) {
        List<Route> routeList = new ArrayList<>();
        for (int i = 1; i < 6; i++) {
            MenuItem menuItem;
            List<MenuItem> menuItems;
            for (EbcMenu e : menuList) {
                if(e.getId() == i){
                    Route route = new Route();
                    route.setId(e.getId());
                    route.setTitle(e.getName());
                    route.setIndex(e.getPath());
                    route.setIcon(e.getIcon());
                    menuItems = new ArrayList<>();
                    for (EbcMenu item : menuList){
                        if(item.getPid() == i){
                            menuItem = new MenuItem();
                            menuItem.setTitle(item.getName());
                            menuItem.setIndex(item.getPath());
//                            menuItem.setComponent(item.getComponent());
                            menuItems.add(menuItem);
                        }
                    }
                    route.setMenuItems(menuItems);
                    routeList.add(route);
                }
            }
        }
        return routeList;
    }


}
